<?php
// 应用公共文件

use App\Models\SystemConfig;
use Illuminate\Support\Facades\Cache;

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = Cache::get("sysconfig_{$group}_{$name}") ?? null;
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = SystemConfig::where($where)->value('value');
                Cache::set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = SystemConfig::where($where)->column('value', 'name');
                Cache::set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

//请求
function request_url($url, $type = 'get', $arr = '', $res = 'json')
{
    //1,初始化
    $ch = curl_init();
    //2,设置参数
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    if ($type == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($arr)));
    }
    //3,调用接口
    $exec = curl_exec($ch);
    //4,关闭
    if ($res == 'json') {
        //成功时会返回 0  所以说下面的if判断不成立、
        if (@curl_errno($ch)) {
            return curl_error($ch);
        } else {
            return json_decode($exec, true);
        }
    }
    curl_close($ch);
}


function random_str($length = 6, $type = '1', $convert = 0)
{
    $config = array(
        '1' => '1234567890',
        '2' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '3' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
        '4' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789',
        '5' => 'ABCDEFGHJKLMNPQRSTUVWXYZ',
    );

    if (!isset($config[$type])) {
        $type = 'string';
    }

    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{
            mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    $first = substr($code, 0, 1);
    if ($first === 0) {
        $code = mt_rand(1, 9) . substr($code, 1);
    }
    return $code;
}


